

class Solution {

    public static void main(String[] args) {
        ListNode node = new ListNode(-1);
        ListNode node5 = new ListNode(5);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node0 = new ListNode(0);

        node0.next = null;
        node4.next = node0;
        node3.next = node4;
        node5.next = node3;
        node.next = node5;

        printNode(node);
        ListNode sortNode = sortList(node);
        printNode(sortNode);


    }

    public static ListNode sortList(ListNode head) {

        if (head.next == null) {
            return head;
        }
        ListNode mid = getMid(head);
        ListNode last = mid.next;
        mid.next = null;
        //对两个子链表排序
        ListNode left = sortList(head);
        ListNode right = sortList(last);

        return merge(right,left);


    }


    //合并两个链表
    public static ListNode merge(ListNode left, ListNode right) {
        ListNode newHead = new ListNode(0);
        ListNode cur = newHead;
        while (left != null && right != null) {
            if (left.val <= right.val) {
                cur.next = left;
                cur = cur.next;
                left = left.next;
            } else {
                cur.next = right;
                cur = cur.next;
                right = right.next;
            }
        }
        if (left != null) {
            cur.next = left;
        }
        if (right != null) {
            cur.next = right;
        }
        return newHead.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    private static void printNode(ListNode node) {
        System.out.print(node.val + "->");
        while (node.next != null) {
            node = node.next;
            System.out.print(node.val + "->");
        }
        System.out.println("");

    }

    //返回链表之间节点
    private static ListNode getMid(ListNode head){
        if(head==null ||head.next==null)    return head;
        ListNode slow = head;
        ListNode faster = head.next;
        while(faster!=null&&faster.next!=null){
            slow = slow.next;
            faster = faster.next.next;
        }
        return slow;
    }


}